package com.demo.maintenance.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import androidx.annotation.NonNull;

import com.demo.maintenance.MyApplication;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileUtils {

    public static String FACE_PATH;

    public static void init() {
        FACE_PATH = MyApplication.getInstance().getExternalFilesDir("file").getAbsolutePath();
    }

    public static void saveImage(@NonNull String oldImagePath, String toPath) {
        try {
            File filePath = new File(FACE_PATH);
            if (!filePath.exists()) {
                boolean isSuccess = filePath.mkdirs();
            }
            File needSaveFile = new File(oldImagePath);
            if (!needSaveFile.exists()) {
                Log.e("monitoring", "非法路径!");
                return;
            }
            Bitmap bitmap = BitmapFactory.decodeStream(new BufferedInputStream(new FileInputStream(oldImagePath)));
            saveFile(bitmap, toPath);
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("monitoring", "保存图片！");
        }
    }

    /**
     * 保存图片
     *
     * @param compressedBitmap /
     * @param path /
     */
    public static void saveFile(@NonNull Bitmap compressedBitmap, String path) {
        File file = new File(path);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            file.delete();
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            compressedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
